package activities;

import fragments.GroupListFragment;
import helper.HttpHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.Session;
import com.matchcalendar.R;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class MatchActivity extends GlobalActivity {
	public enum ListViewGroupsState {
		ING, COMPLETE, NOTREPLYYET, NOTJOIN, JOIN
	}
	public enum GroupState {
		MYGROUP, FRIENDSGROUP
	}
	private Spinner spinnerGroup;
	private ImageButton imageButtonPlusGroup, imageButtonReload;
	private LinearLayout linearLayoutRoot;
	private ViewPager matchPager;
	private List<LinearLayout> barViewList = new ArrayList<LinearLayout>();
	private final int ADD_MATCH_GROUP_REQUEST_CODE = 0;
	private List<GroupListFragment> activityFragmentList = new ArrayList<GroupListFragment>();
	private GroupState nowGroupState;
	private MatchPagerPageChange pageChangeListener;
	
	public GroupState getNowGroupState() {
		return nowGroupState;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_match);
		initGlobalView();
		findView();
		setListenerOrAdapter();
		getButtonMatch().setEnabled(false);
		getButtonMatch().setBackgroundResource(R.color.gray5);
		setIgroupOptions(true);
		new GetMyGroup().execute();
	}

	private void findView() {
		spinnerGroup = (Spinner) findViewById(R.id.spinnerGroup);
		imageButtonPlusGroup = (ImageButton) findViewById(R.id.imageButtonPlusGroup);
		linearLayoutRoot = (LinearLayout) findViewById(R.id.linearLayoutRoot);
		matchPager = (ViewPager) findViewById(R.id.matchPager);
		imageButtonReload = (ImageButton) findViewById(R.id.imageButtonReload);
	}
	
	private void setListenerOrAdapter() {
		List<String> spinnerGroupItems = new ArrayList<String>(2);
		
		pageChangeListener = new MatchPagerPageChange();
		spinnerGroupItems.add("我揪的團");
		spinnerGroupItems.add("別人揪的團");
		spinnerGroup.setAdapter(new ArrayAdapter<String>(MatchActivity.this,
				android.R.layout.simple_spinner_dropdown_item, spinnerGroupItems));
		spinnerGroup.setOnItemSelectedListener(new SpinnerGroupItemSelected());
		imageButtonPlusGroup.setOnClickListener(new ImageButtonPlusGroupOnClickListener());
		matchPager.setAdapter(new MatchPagerAdapter(getSupportFragmentManager()));
		matchPager.setOnPageChangeListener(pageChangeListener);
		imageButtonReload.setOnClickListener(new ImageButtonReloadClick());
	}
	
	private class SpinnerGroupItemSelected implements Spinner.OnItemSelectedListener {
		private boolean init = true;

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int itemIndex, long arg3) {
			if (init)
				init = false;
			else {
				if (itemIndex == 0)
					setIgroupOptions(false);
				else
					setOtherGroupOptions();
			}
		}

		private void setOtherGroupOptions() {
			View view = getLayoutInflater().inflate(R.layout.custom_match_option_bar_othergroup, null);
			TextView textViewJoin = (TextView) view.findViewById(R.id.textViewJoin);
			TextView textViewNotReplyYet = (TextView) view.findViewById(R.id.textViewNotReplyYet);
			TextView textViewNotJoinYet = (TextView) view.findViewById(R.id.textViewNotJoinYet);
			
			imageButtonPlusGroup.setVisibility(View.INVISIBLE);
			linearLayoutRoot.removeViewAt(1);
			barViewList.clear();
			barViewList.add((LinearLayout) view.findViewById(R.id.linearLayoutNotReplyYetColor));
			barViewList.add((LinearLayout) view.findViewById(R.id.linearLayoutNotJoinYetColor));
			barViewList.add((LinearLayout) view.findViewById(R.id.linearLayoutJoinColor));
			textViewNotReplyYet.setOnClickListener(new TextViewPageChangeClick(0));
			textViewNotJoinYet.setOnClickListener(new TextViewPageChangeClick(1));
			textViewJoin.setOnClickListener(new TextViewPageChangeClick(2));
			linearLayoutRoot.addView(view, 1);
			new GetFriendsGroups().execute();
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
		}
	}
	
	private class ImageButtonPlusGroupOnClickListener implements ImageButton.OnClickListener {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(MatchActivity.this, AddMatchGroupActivity.class);
			Bundle bundle = new Bundle();
			
			bundle.putString("myFBID", getIntent().getExtras().getString("myFBID"));
			bundle.putInt("comeFrom", 0);
			intent.putExtras(bundle);
			startActivityForResult(intent, ADD_MATCH_GROUP_REQUEST_CODE);
		}
	}
	
	private class MatchPagerAdapter extends FragmentStatePagerAdapter {
		public MatchPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int index) {
			return activityFragmentList.get(index);
		}

		@Override
		public int getCount() {
			return activityFragmentList.size();
		}
		
		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}
    }
	
	private class MatchPagerPageChange implements ViewPager.OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int index) {
			for (LinearLayout bar: barViewList)
				bar.setBackgroundColor(getResources().getColor(R.color.white));
			barViewList.get(index).setBackgroundColor(getResources().getColor(R.color.gold1));
		}
	}
	
	private class ImageButtonReloadClick implements ImageButton.OnClickListener {

		@Override
		public void onClick(View v) {
			reloadGroups();
		}
	}
	
	private void setIgroupOptions(boolean isInit) {
		View view = getLayoutInflater().inflate(R.layout.custom_match_option_bar_igroup, null);
		TextView textViewExecuting = (TextView) view.findViewById(R.id.textViewExecuting);
		TextView textViewOver = (TextView) view.findViewById(R.id.textViewOver);
		
		if (!isInit) {
			imageButtonPlusGroup.setVisibility(View.VISIBLE);
			linearLayoutRoot.removeViewAt(1);
			new GetMyGroup().execute();
		}
		barViewList.clear();
		barViewList.add((LinearLayout) view.findViewById(R.id.linearLayoutExecutingColor));
		barViewList.add((LinearLayout) view.findViewById(R.id.linearLayoutOverColor));
		textViewExecuting.setOnClickListener(new TextViewPageChangeClick(0));
		textViewOver.setOnClickListener(new TextViewPageChangeClick(1));
		linearLayoutRoot.addView(view, 1);
	}
	
	private class TextViewPageChangeClick implements TextView.OnClickListener {
		private int chooseIndex;
		
		public TextViewPageChangeClick(int chooseIndex) {
			this.chooseIndex = chooseIndex;
		}

		@Override
		public void onClick(View v) {
			matchPager.setCurrentItem(chooseIndex);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
				case ADD_MATCH_GROUP_REQUEST_CODE:
					reloadGroups();
					break;
				default:
					Session.getActiveSession().onActivityResult(MatchActivity.this, requestCode,
							resultCode, data);
			}
		}
	}
	
	public void reloadGroups() {
		for (GroupListFragment fragment: activityFragmentList) {
			fragment.getViewList().clear();
			fragment.getActivityIDList().clear();
		}
		if (nowGroupState == GroupState.MYGROUP)
			new GetMyGroup().execute();
		else if (nowGroupState == GroupState.FRIENDSGROUP)
			new GetFriendsGroups().execute();
	}
	
	private class GetMyGroup extends AsyncTask<Void, Void, String> {
		private ProgressDialog proDialog;

		@Override
		protected void onPreExecute() {
			proDialog = ProgressDialog.show(MatchActivity.this, "查詢中", "正在查詢您揪的團...");
			proDialog.setCancelable(false);
		}

		@Override
		protected String doInBackground(Void... params) {
			String respJsonStr = null;
			
			try {
				JSONObject reqJsonObj = new JSONObject();
				
				reqJsonObj.put("id", getIntent().getExtras().getString("myFBID"));
				HttpResponse resp = HttpHelper.executePost(
						"http://iculture.twgg.org/activity/getMyActivity.php", reqJsonObj.toString());
				respJsonStr = EntityUtils.toString(resp.getEntity());
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return respJsonStr;
		}
		
		@Override
		protected void onPostExecute(String result) {
			try {
				JSONObject respJsonObj = new JSONObject(result);
				JSONArray ingJsonArr = respJsonObj.getJSONArray("ing");
				JSONArray completeJsonArr = respJsonObj.getJSONArray("complete");
				
				nowGroupState = GroupState.MYGROUP;
				activityFragmentList.clear();
				activityFragmentList.add(new GroupListFragment(ListViewGroupsState.ING));
				activityFragmentList.add(new GroupListFragment(ListViewGroupsState.COMPLETE));
				matchPager.getAdapter().notifyDataSetChanged();
				activityFragmentList.get(0).addGroupView(ingJsonArr);
				activityFragmentList.get(1).addGroupView(completeJsonArr);
				pageChangeListener.onPageSelected(0);
				matchPager.setCurrentItem(0);
				proDialog.cancel();
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}
	
	private class GetFriendsGroups extends AsyncTask<Void, Void, String> {
		ProgressDialog proDialog;
		
		@Override
		protected void onPreExecute() {
			proDialog = ProgressDialog.show(MatchActivity.this, "查詢中", "正在查詢朋友揪的團...");
			proDialog.setCancelable(false);
		}

		@Override
		protected String doInBackground(Void... params) {
			String respJsonStr = null;
			
			try {
				JSONObject reqJsonObj = new JSONObject();
				HttpResponse resp;
				
				reqJsonObj.put("id", getIntent().getExtras().getString("myFBID"));
				resp = HttpHelper.executePost("http://iculture.twgg.org/activity/getFriendsActivity.php",
						reqJsonObj.toString());
				respJsonStr = EntityUtils.toString(resp.getEntity());
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return respJsonStr;
		}
		
		@Override
		protected void onPostExecute(String result) {
			try {
				JSONObject respJsonObj = new JSONObject(result);
				JSONArray notReplyYetJsonArr = respJsonObj.getJSONArray("notReplyYet");
				JSONArray notJoinJsonArr = respJsonObj.getJSONArray("notJoin");
				JSONArray joinJsonArr = respJsonObj.getJSONArray("join");
				
				matchPager.setCurrentItem(1);
				nowGroupState = GroupState.FRIENDSGROUP;
				activityFragmentList.clear();
				activityFragmentList.add(new GroupListFragment(ListViewGroupsState.NOTREPLYYET));
				activityFragmentList.add(new GroupListFragment(ListViewGroupsState.NOTJOIN));
				activityFragmentList.add(new GroupListFragment(ListViewGroupsState.JOIN));
				matchPager.getAdapter().notifyDataSetChanged();
				activityFragmentList.get(0).addGroupView(notReplyYetJsonArr);
				activityFragmentList.get(1).addGroupView(notJoinJsonArr);
				activityFragmentList.get(2).addGroupView(joinJsonArr);
				matchPager.setCurrentItem(0);
				proDialog.cancel();
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}
}